package com.fy56.platform.logistics.restful.api.controller;


import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.model.Vip;
import com.fy56.platform.logistics.model.VipOpenidRelate;
import com.fy56.platform.logistics.restful.api.app.authorization.annotation.Authorization;
import com.fy56.platform.logistics.service.wx.IVipBankService;
import com.fy56.platform.logistics.service.wx.IVipService;
import com.fy56.platform.logistics.utils.SmsUtil;
import com.google.common.collect.Maps;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * VIP用户RestController
 * Created by li on 2018-01-29.
 */
@Api(value = "UserManager", description = "用户管理", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private IVipService iVipService;

    @Autowired
    private IVipBankService iVipBankService;

    private static Logger log = Logger.getLogger(UserController.class);

	@ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@RequestMapping(value = "/queryUserList", method = RequestMethod.POST)
	@ResponseBody
	@Authorization
	public List<Vip> queryUserList(
			@ApiParam(value = "用户名",name = "userName",required = true) @RequestParam String userName) {
		Vip model = new Vip();
		model.setName(userName);
		List<Vip> userList = iVipService.select(model);
		return userList;
	}

    @ApiOperation(value = "获得VIP用户信息", notes = "获取信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/getVipUserInfo", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public ResponseEntity getVipUserInfo(
            @ApiParam(value = "微信凭证",name = "openid",required = true) @RequestParam String openid) {
        return new ResponseEntity<>(ResultModel.ok(iVipService.selectByOpenId(openid)), HttpStatus.OK);
    }

    @ApiOperation(value = "获得VIP用户信息", notes = "获取信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/getVipInfo", method = RequestMethod.POST)
    @ResponseBody
    @Authorization
    public ResponseEntity getVipInfo(@RequestParam String id) {
	    Vip vip = iVipService.getVipById(Long.valueOf(id));
        vip.setBankList(iVipBankService.select(Long.valueOf(id)));
        return new ResponseEntity<>(ResultModel.ok(vip), HttpStatus.OK);
    }

    /**
     * @Author Yangjiyu
     * @Date 2018-02-23
     * @Param String mobile 手机号码
     * **根据参数手机号发,调用发送短信接口,获取短信验证码;
     */
	@ApiOperation(value = "发送验证码", notes = "列表信息", httpMethod = "POST" ,produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/sendCode", method = RequestMethod.POST)
    public ResponseEntity sendCode(
            @ApiParam(value = "手机号码" ,required = true) @RequestParam String mobile,
            @ApiParam(value = "功能标识（修改密码：1；注册：2）" ,required = true)@RequestParam int flag){
        Map<String, String> params = Maps.newHashMap();
        params.put("mobileNo",mobile);
        params.put("sendType",flag == 1 ? "findPass" : "reg");
        return new ResponseEntity<>(ResultModel.ok(SmsUtil.sendValidateCode(params)), HttpStatus.OK);
    }

    /**
     * @Author Yangjiyu
     * @Date 2018-02-23
     * @Param String mobile 手机号码
     * **根据参数手机号发,调用发送短信接口,获取短信验证码;
     */
    @ApiOperation(value = "发送验证码", notes = "列表信息", httpMethod = "POST" ,produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/sendVaildateCodeByMobile", method = RequestMethod.POST)
    public ResponseEntity sendVaildateCodeByMobile(
            @ApiParam(value = "手机号码" ,required = true) @RequestParam String mobile,
            @ApiParam(value = "发送方式" ,required = true) @RequestParam String sendType,
            @ApiParam(value = "金融代码" ,required = true) @RequestParam String code,
            @ApiParam(value = "密码" ,required = true) @RequestParam String password){
        Map<String, String> params = Maps.newHashMap();
        params.put("mobileNo",mobile);
        params.put("sendType",sendType);
        params.put("code",code);
        params.put("password",password);

        //修改密码
        if("findPass".equals(sendType)){
            if(!iVipService.existByMobile(mobile)){
                return new ResponseEntity<>(new ResultModel("手机号未注册"), HttpStatus.OK);
            }
        }else if("reg".equals(sendType)){
            if(iVipService.existByMobile(mobile)){
                return new ResponseEntity<>(new ResultModel("手机号已注册"), HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(ResultModel.ok(SmsUtil.sendValidateCode(params)), HttpStatus.OK);

//        //本机调试：虚假手机验证码
//        Map<String, String> map = Maps.newHashMap();
//        map.put("message", "111111");
//        map.put("success", "true");
//        return new ResponseEntity<>(ResultModel.ok(map), HttpStatus.OK);
    }

    /**
     * @Author Yangjiyu
     * @Date 2018-02-23
     * @Param String mobile 手机号码
     * 验证短信验证码
     */
    @ApiOperation(value = "验证短信验证码", notes = "列表信息", httpMethod = "POST" ,produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/checkValidateCodeByMobile", method = RequestMethod.POST)
    public ResponseEntity resetPasswordByValidateCode(
            @ApiParam(value = "验证码" ,required = true) @RequestParam String validateCode, @RequestParam String mobile){
        Map<String, String> params = Maps.newHashMap();
        params.put("mobileNo",mobile);
        params.put("validateCode",validateCode);
        return new ResponseEntity<>(ResultModel.ok(SmsUtil.checkValidateCode(params)), HttpStatus.OK);

//        //本机调试：验证虚假手机验证码
//        Map<String, String> map = Maps.newHashMap();
//        map.put("message", "验证成功");
//        map.put("success", "true");
//        return new ResponseEntity<>(ResultModel.ok(map), HttpStatus.OK);
    }

    @RequestMapping(value = "/editUserInfo", method = RequestMethod.POST)
    @ApiOperation(value = "修改个人信息")
    @Authorization
    public ResponseEntity editUserInfo(@RequestParam String data) {
        Vip model =  JSON.parseObject(data).toJavaObject(Vip.class);
        try {
            return new ResponseEntity(ResultModel.ok(iVipService.update(model)), HttpStatus.OK);
        } catch (Exception e) {
            log.error("修改个人信息失败",e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "修改个人信息失败"), HttpStatus.OK);
        } finally {
            model = null;
        }
    }

    @RequestMapping(value = "/editPass", method = RequestMethod.POST)
    @ApiOperation(value = "修改密码")
    @Authorization
    public ResponseEntity editPass(@RequestParam String data) {
        Vip model =  JSON.parseObject(data).toJavaObject(Vip.class);
        try {
            return new ResponseEntity(ResultModel.ok(iVipService.updatePassByMobile(model)), HttpStatus.OK);
        } catch (Exception e) {
            log.error("修改密码失败",e);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "修改密码"), HttpStatus.OK);
        } finally {
            model = null;
        }
    }


    /**
     * 更新用户FormIds信息，用于发送微信服务通知消息
     *
     */
    @RequestMapping(value = "/editFormIds", method = RequestMethod.GET)
    @ApiOperation(value = "修改FormIds信息")
    @Authorization
    ResponseEntity editFormIds(@RequestParam String mobile, @RequestParam String formId, @RequestParam String openId, @RequestParam String appId) {
        ResponseEntity result = null;
        try {
            Vip vipSearchModel = new Vip();
            vipSearchModel.setMobile(mobile);
            List<Vip> vipList =  iVipService.select(vipSearchModel);
            VipOpenidRelate vorModel = new VipOpenidRelate();
            if (vipList!=null && vipList.size()>0){
                vorModel.setVipMemberId(vipList.get(0).getId());
            }
            vorModel.setAppid(appId);
            vorModel.setFormid(formId);
            vorModel.setOpenid(openId);
            vorModel.setUseFlag("0");
            vorModel.setCreateTime(new Date());
            ResultModel res = iVipService.saveVipOpenid(vorModel);

            result = new ResponseEntity(res, HttpStatus.OK);
        } catch (Exception e) {
            log.error("添加FormIds失败",e);
            result = new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, "添加个人FormIds失败"), HttpStatus.OK);
        }
        log.info("=================添加FormId信息参数===================");
        log.info("mobile: " + mobile + " formId: " + formId + " openId: " + openId+ " appId: " + appId);

        return result;
    }


}